package com.feilx.changgou.gateway;

import com.changgou.utils.IPUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletRequest;

@EnableDiscoveryClient
@SpringBootApplication
public class GateWayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GateWayApplication.class,args);
    }
    /*
    *  创建用户唯一标识，使用ip作为用户唯一标识,ip进行限流
    * */
    @Bean(name="ipKeyResolver")
    public KeyResolver userKeyResover(){
        return  new KeyResolver() {
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                HttpServletRequest request = (HttpServletRequest)exchange.getRequest();
                String ipAddr = IPUtils.getIpAddr(request);
                System.out.println(ipAddr);
                // Mono.just(需要使用用户唯一标识符来标识IP);
                return Mono.just(ipAddr);
            }
        };
    }
}
